//
//  MHCircleHomeModel.m
//  MiaoCircle
//
//  Created by 许正荣 on 2018/4/13.
//  Copyright © 2018年 acgera. All rights reserved.
//

#import "MHDiscoverHomeViewModel.h"
//#import "MHCircleHomeModel.h"
#import "MHHomeCirleItemViewModel.h"
#import "MHSetCirclePropertyViewModel.h"
#import "MHCircleInfo.h"
#import "MHMomentViewModel.h"
#import "MHMomentViewModel.h"
#import "MLCircleInfoMainPageViewModel.h"
#import "MHTestViewModel.h"
#import "MHDiscoverHomeModel.h"
#import "MHHomeDiscoverItemViewModel.h"
#import "MHMomentDetailViewModel.h"
#import "MHWebViewModel.h"
#import "MHAwemeListViewModel.h"
#import "MHAwemeModel.h"
#import "MHMomentDetailViewModel.h"
#import "MHIMMessageTransferHelper.h"
#import "MHCircleUpdateModel.h"
//#import "Aweme.h"
@interface MHDiscoverHomeViewModel ()
@property (nonatomic, readwrite, strong) RACCommand *rightButtonCommand;
@property(nonatomic, strong) NSDateFormatter *formatter;
@end
@implementation MHDiscoverHomeViewModel

- (void)initialize
{
    [super initialize];
    self.title =  LSSTRING("发现");
    
    self.rightImageStr = @"";
    /// 允许下拉刷新
    self.shouldPullDownToRefresh = YES;
    /// 允许上拉加载
    self.shouldPullUpToLoadMore = YES;
    /// 没有数据时，隐藏底部刷新控件
    self.shouldEndRefreshingWithNoMoreData = NO;
    NSDateFormatter*formatter =[[NSDateFormatter alloc]init];
    self.formatter = formatter;
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    
    
    @weakify(self);
    //圈子列表
    RAC(self, circles) = self.requestRemoteDataCommand.executionSignals.switchToLatest;
    /// 数据源
    RAC(self,dataSource) = [RACObserve(self, circles) map:^(NSArray * circles) {
        @strongify(self)
        return [self dataSourceWithCircles:circles];
    }];
    
    self.fetchBannerListCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input) {
        @strongify(self);
        return [[self.services.client getAppAdvertList] mh_parsedResults];
    }];
    
    self.didSelectCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(NSIndexPath * indexPath) {
        @strongify(self);
        
       MHDiscoverHomeModel *circle = self.circles[indexPath.row];
        
        [AXAppDelegate sharedDelegate].currentDiscoverModel = circle;
        
       
        if(circle.vedioObj)
        {
//            Aweme *wame = [Aweme new];
//            wame.
            
//            NSString *detailUrl =  [NSString stringWithFormat:@"%@circles-details-app.html?recentId=",[MHConfigureManager h5BaseUrl]];
//
//            NSURL *url = [NSURL URLWithString: [NSString stringWithFormat:@"%@%ld&userId=%d&userToken=%@",detailUrl,(long)circle.recentId,[MHHTTPService sharedInstance].currentUser.userId,[MHHTTPService sharedInstance].currentUser.userToken]];
//
//
//            //        NSURL *url = [NSURL URLWithString: [[NSString stringWithFormat:@"%@%ld&userId=%d",detailUrl,(long)circle.recentId,[MHHTTPService sharedInstance].currentUser.userId] stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLUserAllowedCharacterSet]]];
//
//            NSURLRequest *request = [NSURLRequest requestWithURL:url];
//            MHWebViewModel * webViewModel = [[MHWebViewModel alloc] initWithServices:self.services params:@{MHViewModelRequestKey:request}];
//            webViewModel.showBottomButton = false;
//            webViewModel.showRightShareJoinTitle = true;
//            webViewModel.rightTitle = circle.isInCircle ? @"进入圈子": @"加入圈子";
//            [self.services pushViewModel:webViewModel animated:YES];
            
//            ;
            
           return  [[[self.services.client getRecentListByNewVideoWithRecentId:circle.recentId pageNum:1 pageSize:3] mh_parsedResults] doNext:^(NSArray *modelArr) {
               MHAwemeListViewModel *viewModel = [[MHAwemeListViewModel alloc] initWithServices:self.services params:@{MHViewModelUtilKey:modelArr,@"MHViewModelShowEnterBtn":@true}];
               [self.services pushViewModel:viewModel animated:YES];
            }];
           
        }else
        {
            
            MHMomentDetailViewModel *detail = [[MHMomentDetailViewModel alloc] initWithServices:self.services params:@{MHViewModelIDKey:@(circle.recentId),MHViewModelIsDetail:@(true)}];
            //        detail.isDetail = YES;
            detail.rightTitle = circle.isInCircle ? @"进入圈子": @"加入圈子";
            [self.services pushViewModel:detail animated:YES];
            return [RACSignal empty];
//            NSString *detailUrl =  [NSString stringWithFormat:@"%@circles-details-app.html?recentId=",[MHConfigureManager h5BaseUrl]];
//
//            NSURL *url = [NSURL URLWithString: [NSString stringWithFormat:@"%@%ld&userId=%d&userToken=%@",detailUrl,(long)circle.recentId,[MHHTTPService sharedInstance].currentUser.userId,[MHHTTPService sharedInstance].currentUser.userToken]];
//
//
//            //        NSURL *url = [NSURL URLWithString: [[NSString stringWithFormat:@"%@%ld&userId=%d",detailUrl,(long)circle.recentId,[MHHTTPService sharedInstance].currentUser.userId] stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLUserAllowedCharacterSet]]];
//
//            NSURLRequest *request = [NSURLRequest requestWithURL:url];
//            MHWebViewModel * webViewModel = [[MHWebViewModel alloc] initWithServices:self.services params:@{MHViewModelRequestKey:request}];
//            webViewModel.showBottomButton = false;
//            webViewModel.showRightShareJoinTitle = true;
//            webViewModel.rightTitle = circle.isInCircle ? @"进入圈子": @"加入圈子";
//            [self.services pushViewModel:webViewModel animated:YES];
        }
        
        return [RACSignal empty];
    }];
    
}


- (instancetype)initWithServices:(id<MHViewModelServices>)services params:(NSDictionary *)params{
    if (self = [super initWithServices:services params:params]) {
        //        MHCircleInfo *info =  [MHCircleInfo new];
        self.showLoacation = [params[@"MHViewModelShowLocation"] boolValue];
        
    }
    return self;
}


/// 请求数据
- (RACSignal *)requestRemoteDataSignalWithPage:(NSUInteger)page{
//    NSDate *tmpStartData =  [NSDate date];
    NSArray * (^mapCircles)(NSArray *) = ^(NSArray *products) {
        if (page == 1) {
            /// 下拉刷新
        } else {
            /// 上拉加载
            products = @[(self.circles ?: @[]).rac_sequence, products.rac_sequence].rac_sequence.flatten.array;
        }
        return products;
    };
    
//    NSDate *currentDate =[NSDate date];
//    NSString *currentDateString =[self.formatter stringFromDate:currentDate];
//    return [[[self.services.client getFindRecentListByNewRule:page > 1 ? 2:1   reFlashTime:currentDateString] mh_parsedResults] map:mapCircles];
    return  [[[self.services.client getFindRecentPagedListWithType:1 pageNum:page pageSize:self.perPage] mh_parsedResults] map:mapCircles];
}

#pragma mark - 辅助方法
- (NSArray *)dataSourceWithCircles:(NSArray *)circles {
    if (MHObjectIsNil(circles) || circles.count == 0) return @[];
    

    NSMutableArray *viewModels = [[circles.rac_sequence map:^(MHDiscoverHomeModel *discoverHome) {
        
        MHHomeDiscoverItemViewModel *viewModel = [[MHHomeDiscoverItemViewModel alloc] initWithCircle:discoverHome];
      
        return viewModel;
    }].array mutableCopy];
//    [viewModels appendObject:addViewModel];
    return viewModels ?: @[] ;
}




@end
